import sys
import os
import json
from datetime import timedelta

from decouple import config
from pathlib import Path

AUTH_USER_MODEL = 'users.User'

BASE_DIR = Path(__file__).resolve().parent.parent

sys.path.insert(0, os.path.join(BASE_DIR, 'fs_admin/apps'))
sys.path.insert(0, os.path.join(BASE_DIR, 'utils'))
sys.path.insert(0, os.path.join(BASE_DIR, 'script'))

SECRET_KEY = config('SECRET_KEY', default='django-insecure-h8k2@9x#v$m!n7&q3w4e5r6t7y8u9i0o1p2a3s4d5f6g7h8j9k0l1z2x3c4v5b6n7m8')

DEBUG = True

ALLOWED_HOSTS = ['*']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'simpleui',
    'corsheaders',
    'csp',
    'rest_framework',
    'users.apps.UsersConfig',
    'shipping.apps.ShippingConfig',
    'opration.apps.OprationConfig',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'opration.middleware.APIStatisticsMiddleware',
]

ROOT_URLCONF = 'fs_admin.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'fs_admin.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': config('DB_HOST'),  
        'PORT': config('DB_PORT'), 
        'USER': config('DB_USER'),  
        'PASSWORD': config('DB_PASSWORD'), 
        'NAME': config('DB_NAME') 
    },
}

# AUTH_PASSWORD_VALIDATORS = json.loads(config('BASE_AUTH_PASSWORD_VALIDATORS'))
AUTH_PASSWORD_VALIDATORS = [
    {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
    {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},
    {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
    {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]

LANGUAGE_CODE = config('LANGUAGE_CODE')

TIME_ZONE = config('TIME_ZONE')

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
STATIC_URL = config('STATIC_URL')
STATIC_ROOT = os.path.join(BASE_DIR, config('STATIC_ROOT'))
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

# URL Settings
# APPEND_SLASH = False
APPEND_SLASH = True

# Media files
MEDIA_URL = config('MEDIA_URL')
MEDIA_ROOT = os.path.join(BASE_DIR, config('MEDIA_ROOT'))

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# CORS
CORS_ALLOW_CREDENTIALS = True  
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
    'http://localhost:9527',
    'http://127.0.0.1:9527',
    'http://localhost:8080',
    'http://127.0.0.1:8080',
    'http://192.168.3.100',  # 添加生产环境IP
    'http://192.168.3.100:80',  # 添加带端口的生产环境IP
)
CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)
CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Admin-Token',  # 添加自定义token头
)

# LOGGING
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
            'style': '{',
        },
        'simple': {
            'format': '{levelname} {asctime} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
        },
        'file': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(BASE_DIR, 'logs', 'django.log'),
            'maxBytes': 1024 * 1024 * 5,  # 5 MB
            'backupCount': 5,
            'formatter': 'verbose',
        },
        'tracking': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(BASE_DIR, 'logs', 'tracking.log'),
            'maxBytes': 1024 * 1024 * 5,  # 5 MB
            'backupCount': 5,
            'formatter': 'verbose',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console', 'file'],
            'level': 'INFO',
            'propagate': True,
        },
        'tracking': {
            'handlers': ['console', 'tracking'],
            'level': 'INFO',
            'propagate': True,
        },
    },
}

# 确保logs目录存在
os.makedirs(os.path.join(BASE_DIR, 'logs'), exist_ok=True)

# 内网HTTP环境安全设置
SECURE_SSL_REDIRECT = False  # 不强制HTTPS重定向
SECURE_PROXY_SSL_HEADER = None  # 不检查SSL代理头
SESSION_COOKIE_SECURE = False  # Session cookie不要求HTTPS
CSRF_COOKIE_SECURE = False  # CSRF cookie不要求HTTPS
SECURE_BROWSER_XSS_FILTER = True  # 保持XSS过滤
SECURE_CONTENT_TYPE_NOSNIFF = True  # 保持内容类型嗅探保护

# Redis
CACHES = {
    "default": {
            "BACKEND": "django_redis.cache.RedisCache", 
            "LOCATION": "redis://127.0.0.1:6379/0",
            "OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient",}},
            "session": {
                    "BACKEND": "django_redis.cache.RedisCache",
                    "LOCATION": "redis://127.0.0.1:6379/1",
                    "OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient",}
                    }
    }
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "session"

# REST_FRAMEWORK
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
    ],
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',
        'rest_framework.parsers.MultiPartParser',
        'rest_framework.parsers.FormParser',
    ], 
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10,
    'EXCEPTION_HANDLER': 'utils.exceptions.custom_exception_handler',
}

# JWT Settings
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=7),  # 访问令牌有效期设为1天
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),  # 刷新令牌有效期设为7天
    'ROTATE_REFRESH_TOKENS': True,  # 刷新令牌时自动更新访问令牌
    'UPDATE_LAST_LOGIN': True,  # 更新用户最后登录时间
}

# CSP
CSP_DEFAULT_SRC = ("'self'",)
CSP_SCRIPT_SRC = ("'self'", "'unsafe-inline'", "'unsafe-eval'",)
CSP_STYLE_SRC = ("'self'", "'unsafe-inline'",)
CSP_IMG_SRC = ("'self'", "data:", "'unsafe-inline'",)
CSP_CONNECT_SRC = ("'self'", )
CSP_FONT_SRC = ("'self'",)
CSP_FRAME_ANCESTORS = ("'self'",)
